//
//  QuickEditBookView.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 10.05.25.
//

import SwiftUI

struct QuickEditBookView: View {
    
    @Environment(\.presentToast) var presentToast
    @Environment(\.presentationMode) var presentationMode;
    @StateObject var viewModel: QuickEditBookViewModel
    @State var selectedBook: AccountingBook? = nil
    @State var selectedCategory: AccountingCategory? = nil
    var onSelectedBook:(AccountingBook)->Void
    
    init(detail: AccountingDetailCombine, onSelectedBook:@escaping (AccountingBook)->Void) {
        self._viewModel = StateObject(wrappedValue: QuickEditBookViewModel(detail: detail))
        self.onSelectedBook = onSelectedBook
    }
    
    var body: some View {
        ScrollView {
            LazyVStack {
                ForEach($viewModel.books) { item in
                    Button(action:{
                        // 切换类别
                        let book = item.wrappedValue
                        if viewModel.detail.book.bookId != book.bookId {
                            selectedBook = book
                        }
                    }) {
                        BookItemView(book: item.wrappedValue, isSelected: item.wrappedValue.bookId == viewModel.selectedBook.bookId)
                            .padding(EdgeInsets(top: 20, leading: 16, bottom: 20, trailing: 16))
                            .background(Color.koiColorBackgroundItem)
                            .cornerRadius(16)
                            .padding(.vertical, 2)
                    }
                }
                Color.clear.frame(height: 30)
            }
            .padding(EdgeInsets(top: 5, leading: 20, bottom: 5, trailing:20)) // 去除边距
        }
        .sheet(item: $selectedBook) { book in
            QuickEditCategoryView(
                selectedBookId: book.bookId,
                onCategorySelect: { selectedCategory in
                    selectedBook = book
                    viewModel.selectedBook = book
                    viewModel.selectedCategory = selectedCategory
                    viewModel.updateBook()
                }
            ).presentationDetents([.large])
        }
        .koiToolbar(title: Text("选择账本"))
        .onChange(of: viewModel.updateState) { value in
            if value == "" { return }
            if value == "success" {
                presentToast(.init(message: "修改成功"))
                onSelectedBook(viewModel.selectedBook)
                presentationMode.wrappedValue.dismiss()
            }
        }
        .onAppear {
            viewModel.loadBooks()
        }
    }
}

@available(iOS 18.0, *)
#Preview {
    QuickEditBookView(detail: AccountingDetailCombine.previewData(), onSelectedBook: {_ in })
}
